<template>
<div id="Order">
  <van-tabs style="flex-shrink: 0;" @change="onSearch()" v-model="active" inverse indicator-color="#2196F3" color="#2196F3" 
    text-color="rgba(0, 0, 0, 0.54)" center :swipe-threshold="5">
    <van-tab>
      <div slot="title" style="line-height: 1.2; height: 96%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
        <span style="font-size: 0.3rem;">租借中</span>
        <span style="font-size: 0.2rem;">({{ status[0] || 0 }})</span>
      </div>
    </van-tab>
    <van-tab>
      <div slot="title" style="line-height: 1.2; height: 96%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
        <span style="font-size: 0.3rem;">已归还</span>
        <span style="font-size: 0.2rem;">({{ status[1] || 0 }})</span>
      </div>
    </van-tab>
    <van-tab>
      <div slot="title" style="line-height: 1.2; height: 96%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
        <span style="font-size: 0.3rem;">已撤销</span>
        <span style="font-size: 0.2rem;">({{ status[2] || 0 }})</span>
      </div>
    </van-tab>
    <!--  v-if="showChaoshi" -->
    <van-tab v-if="showChaoshi">
      <div slot="title" style="line-height: 1.2; height: 96%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
        <span style="font-size: 0.3rem;">超时订单</span>
        <span style="font-size: 0.2rem;">({{ status[3] || 0 }})</span>
      </div>
    </van-tab>
    <van-tab v-if="showChaoshi">
      <div slot="title" style="line-height: 1.2; height: 96%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
        <span style="font-size: 0.3rem;">暂停计费</span>
        <span style="font-size: 0.2rem;">({{ status[4] || 0 }})</span>
      </div>
    </van-tab>
  </van-tabs>
  <div style="display: flex;">
    <van-dropdown-menu style="width: 30%;">
      <van-dropdown-item v-model="chargeStatus" :options="chargeOption" @change="chargeStatusChange"/>
    </van-dropdown-menu>
    <van-dropdown-menu style="width: 40%;">
      <van-dropdown-item v-model="sort" :options="sortOption" @change="chargeSort"/>
    </van-dropdown-menu>
    <div style="width: 30%; display: flex; justify-content: center; font-size: 15px; align-items: center;" @click="findBao.show()">
      <span>查找充电宝</span>
    </div>
  </div>
  <van-search v-model="searchValue" placeholder="请输入" show-action shape="round"> 
    <div slot="label" @click="showAction = true">
      {{ labelName }}
      <van-icon name="arrow-down" />
    </div>       
    <div slot="action" @click="onSearch" class="ft-blue">搜索</div>
  </van-search>
  <div class="flex-body">
    <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="getList">
      <div class="tongji-box" v-for="(item, index) in list" :key="index" @click="showBlank( item )">
        <div class="tongji-item">
          <!-- <div class="tongji-row">
            <div>恢复订单：</div>              
            <van-button v-if="$store.state.userInfo.roleType == 0" round type="info" size="small" @click.stop="huifu( item )">恢复</van-button>
          </div> -->
          <div class="tongji-row" style="height: 1.2rem;">
            <!-- <template v-if="$store.state.userInfo.roleType == 0"> -->
            <template v-if="false">
              <img :src="item.icon" style="width: 1rem; height: 1rem;" @click.stop="showBig( item )"/>
              <div>
                {{ item.nick }}
                <van-button v-if="$store.state.userInfo.roleType == 0 && item.orderStatus == 0" round type="info" size="small" @click.stop="quxiao( item )">取消</van-button>
                <van-button v-if="$store.state.userInfo.roleType == 0 && item.realExpense && item.realExpense > 0" round type="info" size="small" @click.stop="tuikuan( item )">退款</van-button>
              </div>
            </template>
            <template v-else>
              <span>{{ item.nick }}</span>
              <van-button v-if="$store.state.userInfo.roleType == 0 && item.orderStatus == 0" round type="info" size="small" @click.stop="quxiao( item )">取消</van-button>
              <van-button v-if="$store.state.userInfo.roleType == 0 && item.realExpense && item.realExpense > 0" round type="info" size="small" @click.stop="tuikuan( item )">退款</van-button>
            </template>
          </div>
          <div class="tongji-row">
            <div>用户id：</div>
            <div @click.stop="$store.commit('copy', item.userId)">{{ item.userId }}</div>
          </div>
          <div class="tongji-row">
            <div>订单编号：</div>
            <div>{{ item.orderId }}{{item.shopDisplay == 1 ? '*' : ''}}</div>
            <van-button v-if="$store.state.userInfo.roleType == 0 && item.orderStatus == 0" round type="info" size="small" @click.stop="zanting( item )">暂停计费</van-button>
            <van-button v-if="$store.state.userInfo.roleType == 0 && item.orderStatus == 4" round type="info" size="small" @click.stop="zanting( item )">回复计费</van-button>
          </div>
          <div class="tongji-row">
            <div>费用：</div>
            <div>{{ item.realExpense || item.realExpense == 0 ? item.realExpense+'元' : order[ item.orderStatus ] }}</div>
          </div>
          <div class="tongji-row" v-if="item.refundMoney">
            <div>退款金额：</div>
            <div>{{ item.refundMoney }}元</div>
          </div>
          <div class="tongji-row" v-if="$store.state.userInfo.roleType == 0">
            <div>分成明细：</div>
            <div class="ft-blue" @click.stop="lookOrder(item.orderId, true)">查看</div>
          </div>
          <div class="tongji-row" v-if="$store.state.userInfo.roleType == 0 && item.refundMoney">
            <div>退款明细：</div>
            <div class="ft-blue" @click.stop="lookOrder(item.orderId)">查看</div>
          </div>
          <div class="tongji-row">
            <div>租借地点：</div>
            <div class="ft-blue">{{ item.shopName }}({{ item.rentShopId }})</div>
          </div>
          <div class="tongji-row">
            <div>设备编号：</div>
            <div class="ft-blue" @click.stop="$store.commit('copy', item.equipmentSn)">{{ item.equipmentSn }}</div>
          </div>
          <div class="tongji-row">
            <div>充电宝编号：</div>
            <div class="ft-blue" @click.stop="$store.commit('copy', item.chargerSn)">{{ item.chargerSn }}</div>
          </div>
          <div class="tongji-row">
            <div>租借时间：</div>
            <div>{{ item.rentTime }}</div>
          </div>
          <div class="tongji-row" v-if="item.returnTime">
            <div>归还时间：</div>
            <div>{{ item.returnTime }}</div>
          </div>
          <div class="tongji-row" v-if="item.payTime">
            <div>付款时间：</div>
            <div>{{ item.payTime }}</div>
          </div>
        </div>
      </div>
    </van-list>
  </div>  
  
  <van-popup v-model="blank.show"
   position="bottom" :style="{ height: '100%' }">
    <div class="page-blank">
      <van-nav-bar title="订单详情" left-arrow @click-left="blank.show = false"/>
      <van-cell-group>
        <van-field readonly label="租借地点"   :value="info.shopName"/>
        <van-field readonly label="租借时间"   :value="info.rentTime"/>
        <van-field readonly label="租借方式"   :value="info.orderType == 1 ? '微信租借' : '支付宝租借'"/>
        <van-field readonly label="归还时间"   :value="info.returnTime || order[ info.orderStatus ]"/>
        <van-field readonly label="归还地点"   :value="info.returnShopId"/>
        <van-field readonly label="租借设备sn" :value="info.equipmentNum"/>
        <van-field readonly label="归还设备sn" :value="info.returnEquipmentSn"/>
        <van-field readonly label="应付金额"   :value="info.shouldExpense || info.shouldExpense == 0 ? info.shouldExpense + '￥' : order[ info.orderStatus ]"/>
        <van-field readonly label="实付金额"   :value="info.realExpense || info.realExpense == 0 ? info.realExpense + '￥' : order[ info.orderStatus ]"/>
        <van-field readonly label="订单编号"   :value="info.orderId"/>
        <van-field readonly label="充电宝编号" :value="info.chargerSn"/>
        <van-field readonly label="订单状态"   :value="order[ info.orderStatus ]"/>
        <van-field readonly label="付费状态"   :value="charge[ info.chargeStatus ]"/>
      </van-cell-group>
    </div>
  </van-popup>
  
  <van-popup v-model="detailBlank" position="bottom" :style="{ height: '100%' }">
    <div class="page-blank">
      <van-nav-bar :title="detailType ? '分成明细' : '退款明细'" left-arrow @click-left="detailBlank = false"/>
      <div v-if="detailType">
        <van-cell-group v-for="(item, index) in detailList" :key="index">
          <van-field readonly :label="item.nick" :value="item.incomeMoney"/>
        </van-cell-group>
      </div>
      <div v-else>
        <van-cell-group v-for="(item, index) in detailList" :key="index">
          <van-field readonly :label="item.nick" :value="item.refundIncome"/>
          <van-field readonly label="退款时间" :value="item.createTime"/>
        </van-cell-group>
      </div>
    </div>
  </van-popup>

  <van-dialog v-model="showTuikuan.blank" title="退款" show-cancel-button @confirm="submitTuikuan">
    <van-cell-group>
      <van-field v-model="showTuikuan.money" placeholder="请输入" label="退款金额"/>
    </van-cell-group>
  </van-dialog>

  <!-- <van-dialog v-model="findBao.blank" title="查找充电宝" show-cancel-button :showConfirmButton="false" cancelButtonText="关闭">
    <van-cell-group>
      <van-field v-model="findBao.message" placeholder="请查找" readonly/>
    </van-cell-group>
    <van-cell-group>
      <van-field v-model="findBao.message" placeholder="请查找" readonly/>
    </van-cell-group>
  </van-dialog> -->

  <van-action-sheet v-model="showAction" :actions="actions" @select="selectAction" cancel-text="取消" @cancel="showAction = false"/>

  <van-dialog v-model="findBao.blank" title="查找充电宝" show-cancel-button :showConfirmButton="false" cancelButtonText="关闭">
    <van-search v-model="findBao.chargerSn" placeholder="请输入" show-action shape="round"> 
      <div slot="label">充电宝编号</div>       
      <div slot="action" @click="findBao.find()" class="ft-blue">查找</div>
    </van-search>
    <van-cell-group>
      <van-field v-model="findBao.message" placeholder="请查找" readonly/>
    </van-cell-group>
  </van-dialog>

  <van-image-preview v-model="bigShow" :images="images">
    <template v-slot:index>{{  }}</template>
  </van-image-preview>
</div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';
import axios from '@/utils/request';

@Component
export default class Order extends Vue {
  detailList: any = []
  detailBlank: any = false
  detailOrder: any = 0
  detailType: any = false
  lookOrder(orderId: any, type: any) {
    let url = '/api/IncomeItemController/orderRefundItem';
    if (type) url = '/api/IncomeItemController/orderIncomeItem';
    this.$toast.loading({ mask: true, message: '加载中...', duration: 0 });
    axios.get(url, { orderId }).then((res: any) => {
      this.$toast.clear();
      this.detailOrder = orderId;
      this.detailType = type || false;
      this.detailList = res || [];
      this.detailBlank = true;
    }).catch(() => {
      this.$toast.clear();
    });
  }

  bigShow: any = false
  images: any = []
  showBig(item: any) {
    this.images = [ item.icon ];
    this.bigShow = true;
  }

  sort: any = 0
  sortOption: any = [
    { text: '租借时间', value: 0 },
    { text: '归还时间从后往前', value: 1 },
    { text: '归还时间从前往后', value: 2 },
    { text: '付款时间从后往前', value: 3 },
    { text: '付款时间从前往后', value: 4 }
  ]
  
  chargeStatus: any = 4
  chargeOption: any = [
    { text: '全部订单', value: 4 },
    { text: '未付款', value: 0 },
    { text: '待支付', value: 1 },
    { text: '已付款', value: 2 },
    { text: '退款', value: 3 }
  ]
  chargeStatusChange() {
    this.page = 1
    this.list = [];
    this.loading = true;
    this.finished = false;
    this.getList();
  }

  active: any = 0  
  status: any = []
  showChaoshi: boolean = false
  order: any = [ '租借中', '已归还', '已撤销', '超时', '暂停计费' ]
  charge: any = [ '未付款', '待支付', '已付款', '退款' ]

  list: any = []

  loading: boolean = false
  finished: boolean = false
  page: any = 1
  searchValue: any = ''
  
  showAction: any = false
  labelName: any = '订单编号'
  actions: any = [
    { name: '订单编号' },
    { name: '充电宝编号' },
    { name: '机柜编号' },
    { name: '手机号' },
    { name: '信用订单号' },
    { name: '支付单号' }
  ]
  selectAction(obj: any) {
    this.labelName = obj.name;
    this.showAction = false;
    this.onSearch();
  }

  chargeSort(sort: any) {
    this.sort = sort;
    this.onSearch();
  }
  
  getList() {
    let page = this.page, size = 10, orderStatus = this.active, findSubordinate = true;
    let chargeStatus = this.chargeStatus == 4 ? null : this.chargeStatus;
    let sortArr = [ null, 'return_time desc', 'return_time asc', 'pay_time desc', 'pay_time asc' ];
    let queryKey: any = { page, size, orderStatus, chargeStatus, sort: sortArr[this.sort] };
    if ( this.labelName == '订单编号' ) { queryKey.orderNum = this.searchValue || null; }
    else if ( this.labelName == '充电宝编号' ) { queryKey.chargerSn = this.searchValue || null; }
    else if ( this.labelName == '机柜编号' ) { queryKey.terminalSn = this.searchValue || null; }
    else if ( this.labelName == '手机号' ) { queryKey.phone = this.searchValue || null; }
    else if ( this.labelName == '支付单号' ) { queryKey.payOrderId = this.searchValue || null; }
    else { queryKey.creditId = this.searchValue || null; }
    axios.get('/api/orderFormController/manageOrder', queryKey).then((res: any) => {
      if(this.active != orderStatus) return ;
      let json = res || {}; 
      let list = json.list || [];
      this.page = page + 1;
      this.loading = false;
      this.list.push( ...list );
      if(json.isLastPage) this.finished = true;
      // if( this.finished ) {
      //   let all = 0;
      //   let aaa = 0;
      //   this.list.forEach((ele: any) => {
      //     let realExpense = ele.realExpense || 0;
      //     let refundMoney = ele.refundMoney || 0;
      //     // all = all + realExpense;
      //     // aaa = aaa + refundMoney;
      //     if ( realExpense == 99 && refundMoney == 0 ) {
      //       all = all + realExpense;
      //     }
      //   });
      //   console.log( '总计金额：' + all );
      //   console.log( '退款金额：' + aaa );
      // }
    }).catch((err: any) => {
      this.loading = false;
      this.finished = true;
    });
  }

  tuikuan(item: any) {    
    this.showTuikuan.orderId = item.orderId;
    this.showTuikuan.money = '';
    this.showTuikuan.blank = true;
  }
  huifu(item: any) {    
    axios.post('/api/orderFormController/recoveryOrder')
  }

  zanting(info: any) {
    this.$dialog.confirm({ 
      message: `订单号${ info.orderId }，确定要对该订单${ info.orderStatus == 0 ? '暂停计费' : '回复计费' }吗?`,       
    }).then(() => {
      axios.post(`/api/orderFormController/stopOrder`, { query: { orderId: info.orderId, type: info.orderStatus == 0 ? '1' : '2' } }).then((res: any) => {
        this.$toast(`${ info.orderStatus == 0 ? '暂停计费' : '回复计费' }成功！`);
        this.onSearch();
      });
    });
  }

  quxiao(item: any) {    
    this.$dialog.confirm({ 
      message: `取消功能是为了充电宝损坏，业务员取回充电宝设置的，擅自给用户取消订单会导致丢失充电宝，确定要取消该订单吗？`,       
    }).then(() => {
      axios.post(`/api/orderFormController/cancelOrder`, { query: { orderId: item.orderId } }).then((res: any) => {
        this.$toast('退款成功');
        this.onSearch();
      });
    });
  }

  onSearch() {
    this.page = 1;
    this.list = [];
    this.finished = false;
    this.loading = true;
    this.$router.replace({ name: this.$route.name, query: { active: this.active } });
    this.getList();
  }

  blank: any = {
    show: false,
    list: []
  }
  info: any = {}
  showBlank(item: any) {
    this.info = JSON.parse( JSON.stringify( item ) );
    this.blank.show = true;   
  }

  showTuikuan: any = {
    blank: false,
    orderId: '',
    money: ''
  }
  submitTuikuan() {
    if( this.showTuikuan.money ) {
      axios.post(`/api/borrow/refundOrderByPayOrderId/${ this.showTuikuan.orderId }?money=${ this.showTuikuan.money }`).then((res: any) => {
        this.$toast('退款成功');
        this.onSearch();
      });
    } else {
      this.$toast('请输入正确的金额');
    }
  }

  findBao: any = {
    blank: false,
    chargerSn: '',
    message: '',
    find: () => {
      let chargerSn: any = this.findBao.chargerSn;
      if ( !chargerSn ) { this.findBao.message = ''; return ; }
      axios.get('/api/chargerPlaController/chargerStatus', { chargerSn }).then((res: any) => {
        if ( res ) {
          this.findBao.message = `${ chargerSn }在机柜${ res }中`;
        } else {
          this.findBao.message = `${ chargerSn }不在机柜中`;
        }
      });
    },
    show: () => {
      this.findBao.chargerSn = '';
      this.findBao.message = '';
      this.findBao.blank = true;
    }
  }

  created() {
    if(this.$store.state.userInfo.role.delayingPurchases == 1 || this.$store.state.userInfo.roleType == 0) this.showChaoshi = true;
    if(this.$route.query.active) this.active = Number(this.$route.query.active);
    axios.get('/api/orderFormController/manageOrderNum').then((res: any) => {
      this.status = res || [];
    });
  }
  
};
</script>

<style lang="scss">
#Order {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .van-tab {
    .van-ellipsis {
      height: 100%;
      &>div {
        height: 100%;
      }
    }
  }
}
</style>

